<template>
    <div class="container flex-container">
        <div class="left">
            <n-card size="large">
                <template #header>
                    <n-h2>{{ question.title }}
                        <n-tag v-if="question.essential" :bordered="false" size="large" type="info">精品</n-tag>
                    </n-h2>
                    <div class="creator">
                        <n-avatar
                            :round="true"
                            :size="36"
                            :style="{color: 'white', backgroundColor: 'orange', fontSize: '18px', cursor: 'pointer'}"
                        >{{ question.username.toString().substring(0, 1) }}
                        </n-avatar>
                        <router-link to="">
                            <n-text class="name" type="success" @click="handleClickCreator">{{
                                    question.username
                                }}
                            </n-text>
                        </router-link>
                        <n-text class="update-time" depth="3">更新于 {{
                                $dayjs(postUpdateTime).format('YYYY 年 M 月 D 日')
                            }}
                        </n-text>
                    </div>
                </template>
                <n-space :vertical="true" size="large">
                    <div v-highlight class="content" v-html="question.content"></div>
                    <n-switch v-model:value="showSupplement">
                        <template #checked>
                            展开代码执行细节
                        </template>
                        <template #unchecked>
                            折叠代码执行细节
                        </template>
                    </n-switch>
                    <n-collapse-transition :show="showSupplement">
                        <n-descriptions :column="2" label-placement="left" title="补充说明">
                            <n-descriptions-item v-if="question.executionResult" label="执行结果">
                                <n-ellipsis :tooltip="false" expand-trigger="click" line-clamp="4">
                                    {{ question.executionResult }}
                                </n-ellipsis>
                            </n-descriptions-item>
                            <n-descriptions-item v-if="question.errorMessage" label="报错信息">
                                <n-ellipsis :tooltip="false" expand-trigger="click" line-clamp="4">
                                    {{ question.errorMessage }}
                                </n-ellipsis>
                            </n-descriptions-item>
                            <n-descriptions-item v-if="question.errorRow" label="出错的行">
                                {{ question.errorRow }}
                            </n-descriptions-item>
                            <n-descriptions-item v-if="question.errorColumn" label="出错的列">
                                {{ question.errorColumn }}
                            </n-descriptions-item>
                            <n-descriptions-item v-if="question.completeCode" label="完整代码">
                                <n-ellipsis :tooltip="false" expand-trigger="click" line-clamp="4">
                                    <n-code :code="question.completeCode" :language="programming_language"
                                            :word-wrap="true"/>
                                </n-ellipsis>
                            </n-descriptions-item>
                            <n-descriptions-item v-if="question.errorCode" label="出错代码">
                                <n-ellipsis :tooltip="false" expand-trigger="click" line-clamp="4">
                                    <n-code :code="question.errorCode" :language="programming_language"
                                            :word-wrap="true"/>
                                </n-ellipsis>
                            </n-descriptions-item>
                        </n-descriptions>
                    </n-collapse-transition>
                </n-space>
                <template #footer>
                    <n-space size="small" style="justify-content:space-between;">
                        <div class="question-tag">
                            <n-text>标签:</n-text>
                            <div>
                                <n-tag v-if="question.reward"
                                       :color="{ color: '#f0c560', textColor: '#fff', borderColor: '#f0c560' }"
                                       size="small">
                                    ￥{{ question.reward }}
                                </n-tag>
                                <n-tag v-for="tag in question.tags" :bordered="false" size="small" type="success">{{
                                        tag.name
                                    }}
                                </n-tag>
                            </div>
                        </div>
                        <div v-if="userStore.role === 2">
                            <n-button v-if="!question.essential" secondary type="info" @click="updateExcellentPost">加精
                            </n-button>
                            <n-button v-else secondary type="error" @click="updateExcellentPost">去精</n-button>
                        </div>
                    </n-space>
                </template>
            </n-card>
            <div class="answer-wrapper">
                <n-card
                    v-if="answerList.length"
                    :segmented="{content: true}"
                >
                    <template #header>
                        <n-text style="font-weight: bold;">{{ answerList.length }} 个回答</n-text>
                    </template>
                    <template #header-extra>
                        <n-button-group size="small">
                            <n-button ghost @click="updateAnswerList(questionId, 'vote_count')">
                                <template #icon>
                                    <n-icon>
                                        <hotjar/>
                                    </n-icon>
                                </template>
                                好评
                            </n-button>
                            <n-button ghost @click="updateAnswerList(questionId, 'create_time')">
                                <template #icon>
                                    <n-icon>
                                        <ClockRegular/>
                                    </n-icon>
                                </template>
                                最新
                            </n-button>
                        </n-button-group>
                    </template>
                </n-card>
                <template v-for="item in answerList" :key="item.id">
                    <Answer :answer="item" :is-questioner="isQuestioner"
                            :is-solved="question.isSolved"
                            :programming-language="programming_language"
                            :reward="question.reward"></Answer>
                </template>
            </div>
            <div v-if="!isSubmitted" class="writing">
                <n-card title="撰写回答">
                    <div id="vditor"></div>
                    <template #action>
                        <n-space justify="space-between">
                            <n-button size="large" type="success" @click="handleSubmitAnswer">提交回答</n-button>
                            <n-button @click="showDrawer = !showDrawer">补充代码分析细节</n-button>
                        </n-space>
                    </template>
                </n-card>
                <n-card v-show="showDrawer" title="代码分析细节">
                    <n-scrollbar>
                        <n-form ref="moreInfoFormRef" :model="answer" size="large">
                            <n-grid :cols="24" :x-gap="24">
                                <n-form-item-gi :span="12" label="错误类型">
                                    <n-select v-model:value="answer.errorType" :options="options"/>
                                </n-form-item-gi>
                                <n-form-item-gi :span="12" label="出错代码的那一行">
                                    <n-input
                                        v-model:value="answer.errorRow"
                                        type="text"
                                    />
                                </n-form-item-gi>
                                <n-form-item-gi :span="12" label="出错代码的那一列">
                                    <n-input
                                        v-model:value="answer.errorColumn"
                                        type="text"
                                    />
                                </n-form-item-gi>
                                <n-form-item-gi :span="12" label="出错代码的那一行">
                                    <n-input
                                        v-model:value="answer.errorCode"
                                        :autosize="{ minRows: 3 }"
                                        type="textarea"
                                    />
                                </n-form-item-gi>
                                <n-form-item-gi :span="12" label="错误分析">
                                    <n-input
                                        v-model:value="answer.errorDesc"
                                        type="text"
                                    />
                                </n-form-item-gi>
                                <n-form-item-gi :span="12" label="修改后的代码行">
                                    <n-input
                                        v-model:value="answer.modifiedCode"
                                        :autosize="{ minRows: 3 }"
                                        type="textarea"
                                    />
                                </n-form-item-gi>
                                <n-form-item-gi :span="12" label="修改前的完整代码">
                                    <n-input
                                        v-model:value="answer.codeBeforeChange"
                                        :autosize="{ minRows: 3 }"
                                        type="textarea"
                                    />
                                </n-form-item-gi>
                                <n-form-item-gi :span="12" label="修改后的完整代码">
                                    <n-input
                                        v-model:value="answer.codeAfterChange"
                                        :autosize="{ minRows: 3 }"
                                        type="textarea"
                                    />
                                </n-form-item-gi>
                            </n-grid>
                        </n-form>
                    </n-scrollbar>
                </n-card>
            </div>
        </div>
        <!--<div class="right">-->
        <!--    <n-card>-->
        <!--        <div class="user-info">-->
        <!--            <n-avatar-->
        <!--                :round="true"-->
        <!--                :size="50"-->
        <!--                :style="{color: 'white', backgroundColor: 'orange', fontSize: '25px', cursor: 'pointer', width: '50px'}"-->
        <!--            >{{ question.username.toString().substring(0, 1) }}-->
        <!--            </n-avatar>-->
        <!--            <span class="name-desc">-->
        <!--                <n-text class="name">{{ question.username }}</n-text>-->
        <!--                <n-text class="desc" depth="3">{{ selfIntroduction }}</n-text>-->
        <!--            </span>-->
        <!--        </div>-->
        <!--        <n-divider/>-->
        <!--        <div class="like-view">-->
        <!--            <div class="like">-->
        <!--                <n-icon color="#42b983" size="25">-->
        <!--                    <Coins></Coins>-->
        <!--                </n-icon>-->
        <!--                <n-text>获得积分 {{ question.credit }}</n-text>-->
        <!--            </div>-->
        <!--            <div class="view">-->
        <!--                <n-icon color="#42b983" size="25">-->
        <!--                    <Eye/>-->
        <!--                </n-icon>-->
        <!--                <n-text>帖子被浏览 {{ question.viewCount }}</n-text>-->
        <!--            </div>-->
        <!--        </div>-->
        <!--    </n-card>-->
        <!--</div>-->
        <!--<n-drawer v-model:show="showDrawer" :width="500">-->
        <!--    <n-drawer-content closable title="代码分析细节">-->
        <!--    </n-drawer-content>-->
        <!--</n-drawer>-->
    </div>
</template>

<style scoped>
.flex-container {
    display: flex;
    gap: 1vw;
}

.left {
    width: 100%;
}

.writing {
    display: flex;
    gap: 1vw;
}

/*.right {*/
/*    flex: 1;*/
/*}*/

.creator {
    display: flex;
    align-items: center;
    gap: 0.5vw;
    font-size: 16px;
}

.creator .name {
    font-weight: 600;
}

/*.user-info {*/
/*    display: flex;*/
/*    align-items: center;*/
/*    gap: 1vw;*/
/*}*/

/*.user-info .name-desc {*/
/*    display: flex;*/
/*    flex-direction: column;*/
/*    flex: 1;*/
/*}*/

.name-desc .name {
    font-size: 16px;
}

/*.like-view {*/
/*    display: flex;*/
/*    flex-direction: column;*/
/*    gap: 1vh;*/
/*}*/

/*.like-view .like, .like-view .view {*/
/*    display: flex;*/
/*    align-items: center;*/
/*    gap: 0.8vw;*/
/*}*/

.answer-wrapper {
    margin: 1vw 0;
}

.question-tag {
    display: flex;
    gap: 0.5vw;
    align-items: baseline;
    justify-content: center;
}
</style>

<script setup>
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getQuestion, partialUpdateQuestion } from '../api/question'
import { useMessage } from 'naive-ui'
import { ClockRegular, Hotjar } from '@vicons/fa'
import Answer from '../components/Answer.vue'
import { insertAnswer, listAnswers } from '../api/answer'
import { useUserStore } from '../store/user'
import Vditor from 'vditor'
import 'vditor/dist/index.css'
import { getCurrentUserId, isEmpty } from '../utils/mini-lodash'
import { partialUpdateUser } from '../api/user'

const vditor = ref(null)
window.$message = useMessage()
const message = useMessage()
const $route = useRoute()
const showSupplement = ref(false)
const showDrawer = ref(true)
const question = ref({
    title: '',
    content: '',
    tags: [],
    username: '',
    updateTime: undefined,
    createTime: undefined,
    viewCount: 0,
    starCount: 0,
    introduction: undefined,
    avatar: undefined,
    reward: 0,
    isSolved: false,
    essential: false,
    questioner: undefined,
    executionResult: '',
    errorMessage: '',
    completeCode: '',
    errorCode: '',
    errorRow: '',
    errorColumn: '',
})
let programming_language = 'C++'
let questionId = $route.params.id
let answerList = ref([])
const updateAnswerList = (questionId, orderColumn) => {
    listAnswers(questionId, orderColumn).then(res => {
        answerList.value = res.data
        checkSubmitAnswer()
    })
}

const isQuestioner = ref(false)
const checkQuestioner = () => {
    if (!isEmpty(userStore.username)) {
        isQuestioner.value = userStore.username === question.value.username
    }
}
const isSubmitted = ref(false)
const checkSubmitAnswer = () => {
    let target = answerList.value.find(answer => {
            return answer.username === userStore.username
        },
    )
    isSubmitted.value = target !== undefined
}

onMounted(() => {
        getQuestion(questionId).then(res => {
            question.value = { ...res.data }
            document.title = res.data.title
            programming_language = res.data.tags[0]?.name
            checkQuestioner()
            checkSubmitAnswer()
        })
        updateAnswerList(questionId, 'create_time')
        if (!isSubmitted.value) {
            vditor.value = new Vditor('vditor', {
                after: () => {
                    vditor.value.setValue('', true)
                },
                // height: 500,
                'resize': {
                    'enable': true,
                },
                // width: 500,
                icon: 'material',
                mode: 'wysiwyg',
                tab: '    ',
                placeholder: '内容描述',
                typewriterMode: true,
                undoDelay: 1500,
                hint: {
                    emojiTail: '设置常用表情',
                },
                counter: {
                    enable: true,
                },
                preview: {
                    hljs: {
                        lineNumber: true,
                        style: 'native',
                    },
                },
                toolbar: [
                    'emoji', 'headings', 'bold', 'italic',
                    'strike', 'link', 'ordered-list', 'check', '|',
                    'quote', 'line', 'code', 'inline-code', 'fullscreen',
                    'edit-mode', '|', 'undo', 'redo', 'code-theme',
                    'content-theme', 'preview', 'help', 'outline',
                ],
            })
        }
    },
)
const postUpdateTime = computed(() => {
    return question.value.updateTime === null ? question.value.createTime : question.value.updateTime
    },
)
const selfIntroduction = computed(() => {
    return isEmpty(question.value.introduction) ? '这个人很神秘，什么都没有写' : question.value.introduction
    },
)

const userStore = useUserStore()
const answer = ref({
    questionId: undefined,
    content: '',
    answerer: undefined,
    modifiedCode: '',
    errorCode: '',
    errorType: '',
    errorDesc: '',
    errorColumn: '',
    errorRow: '',
    codeBeforeChange: '',
    codeAfterChange: '',
})
const handleSubmitAnswer = async () => {
    if (userStore.token === '') {
        message.warning('你没有权限，请登录后再回答')
    } else if (isEmpty(vditor.value.getValue())) {
        message.error('请输入内容再提交！')
    } else {
        answer.value.content = vditor.value.getValue()
        await insertAnswer(questionId, answer.value).then(res => {
            if (res.code === '201') {
                answer.value.content = ''
                vditor.value.setValue('')
            }
        })
        await updateAnswerList(questionId, 'create_time')
        let currentUserId = getCurrentUserId()
        await partialUpdateUser(currentUserId, { credit: userStore.credit + 2 })
        message.success('提交成功, 你获得2积分！')
    }
}

const updateExcellentPost = () => {
    question.value.essential = !question.value.essential
    partialUpdateQuestion(questionId, { essential: question.value.essential }).then(res => {
        if (res.code === '200') {
            if (question.value.essential) {
                message.success('已设置为精品贴！')
            } else {
                message.info('设置为普通帖')
            }
        }
    })
}

const router = useRouter()
const handleClickCreator = () => {
    router.push({
        name: 'User',
        params: { id: question.value.questioner },
    })
}

const options = [
    {
        label: '语法错误',
        value: '语法错误',
    },
    {
        label: '逻辑错误',
        value: '逻辑错误',
    },
    {
        label: '运行时错误',
        value: '运行时错误',
    },
]
</script>
